package com.dzm.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.dzm.properties.OssProperties;
import com.dzm.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 作者：Dzm
 * 时间：2024-08-31-10:21
 * 功能：
 */

@Service
public class FileServiceImpl implements FileService {

    @Override
    public String upload(MultipartFile file) {

        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = OssProperties.ENDPOINT;
        // 填写Bucket名称，例如examplebucket。
        String bucketName = OssProperties.BUCKET_NAME;
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        //获取后缀名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = format + "/" + uuid + suffix;

        // 创建OSSClient实例。
        String accessKey = OssProperties.ACCESS_KEY;
        String accessSecret = OssProperties.ACCESS_SECRET;
        OSS ossClient = new OSSClientBuilder().build(endpoint, OssProperties.ACCESS_KEY, OssProperties.ACCESS_SECRET);

        try {
            ossClient.putObject(bucketName, objectName, file.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        //https://daxigua-dzm.oss-cn-shenzhen.aliyuncs.com/2024/08/20/f8ae302b02fa49b29a05efeed9369d02.jpg
        return "https://" + bucketName + "." + endpoint + "/" + objectName;
    }
}
